package com.lry.sso.auth.common.util;

import com.lry.sso.auth.common.bean.RequestInfoContext;
import com.lry.sso.auth.common.bean.UrlSession;
import com.lry.sso.auth.common.constant.LoginAuthorizationConstant;
import com.lry.sso.common.util.IpUtil;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 *
 *
 * @author 李瑞益
 * @date 2019/11/23
 */
public class AuthUtil {

//    public static final Logger logger = LoggerFactory.getLogger(AuthUtil.class);

//    public static JwtTokenService getJwtTokenService(){
//        return SpringUtil.getBean(JwtTokenService.class);
//    }
    /**
     * 获取请求中的token
     * @param request
     * @return
     */
    public static String getTokenForUrl(HttpServletRequest request){
        String tokens = request.getHeader(LoginAuthorizationConstant.TOKEN_HEADER);
//        logger.info(LoginAuthorizationConstant.TOKEN_HEADER+" : " + tokens);
        if (!StringUtils.isEmpty(tokens)) {
            return tokens.replaceAll("Bearer ", "");
        }
        return null;
    }

//    public static SessionInfo getSessionInfo(String token){
//        SessionInfo sessionInfo = null;
//        try {
//            KeyConfiguration keyConfiguration = SpringUtil.getBean(KeyConfiguration.class);
//            sessionInfo = JWTHelper.getInfoFromToken(token, keyConfiguration.getUserPubKey());
//        }catch (ExpiredJwtException e) {
//            logger.error("token过期：{}", e.getMessage());
//            throw new SysInvocationException(SsoErrorEnum.TOKEN_EXPIRE);
//        } catch (Exception e) {
//            logger.error("token解析失败，可能不正确获取无效：{}", e.getMessage());
//            e.printStackTrace();
//            throw new SysInvocationException(SsoErrorEnum.TOKEN_PARSE.code(), "token解析失败，无效的token");
//        }
//        return sessionInfo;
//    }

    public static UrlSession getUrlSession(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
//        logger.info("请求的url：{}",requestURL.toString());
        String userIP = IpUtil.getUserIP(request);
//        logger.info("用户ip：{}",userIP);
        UrlSession result = new UrlSession();
        result.setIp(userIP);
        result.setApi(request.getRequestURI());
        result.setUrl(requestURL.toString());
        return result;
    }

    /**
     * 获取存储redis的key（5次锁定key）
     * @param userId
     * @return
     */
    public static String getLoginPwdTimesKey(String userId){
        UrlSession urlSession = RequestInfoContext.getUrlSession();
        return LoginAuthorizationConstant.LOGIN_PWD_TIMES_KEY_PRIFEX +urlSession.getIp()+
                LoginAuthorizationConstant.SEPARATOR+ userId;
    }

    /**
     * 获取存储redis的key（ip锁定key）
     * @param userId 用户id
     * @return
     */
    public static String getLoginIpTimesKey(String userId){
        UrlSession urlSession = RequestInfoContext.getUrlSession();
        return LoginAuthorizationConstant.LOGIN_IP_TIMES_KEY_PRIFEX +urlSession.getIp()+
                LoginAuthorizationConstant.SEPARATOR+ userId;
    }

    /**
     * 获取存储redis的用户key
     * @param userId 用户id
     * @return
     */
    public static String getLoginJwtKey(String userId) {
        return LoginAuthorizationConstant.LOGIN_JWT_KEY_PRIFEX+userId;
    }

    /**获取局部会话客户端的key*/
    public static String getClientLoginJwtKey(String userId){
        return LoginAuthorizationConstant.CLIENT_LOGIN_JWT_KEY_PREFEX + userId;
    }

}
